<template>
  <div class="app-container">
    <div v-if="user">
      <el-row :gutter="20">
        <!-- User Card -->
        <el-col :span="6" :xs="24">
          <user-card :user="user" />
        </el-col>

        <!-- Change Password Form & Key Card -->
        <el-col :span="14" :xs="24">
          <!-- Change Password Card -->
          <el-card class="responsive-card">
            <div slot="header">
              <span>修改密码</span>
            </div>
            <el-form :model="passwordForm" ref="passwordForm" label-width="100px" class="password-form">
              <el-form-item label="旧密码" prop="oldPassword" :rules="oldPasswordRules">
                <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入旧密码" />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword" :rules="newPasswordRules">
                <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
              </el-form-item>
              <el-form-item label="请再输入一遍新密码" prop="confirmPassword" :rules="confirmPasswordRules">
                <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再输入一遍新密码" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSubmit">提交</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- Key Card -->
          <el-card class="responsive-card" style="margin-top: 20px;">
            <div slot="header">
              <span>密钥</span>
            </div>
            <ColoredCard title="激活使用说明" description="开发者需要在此处复制密钥并导入源代码的某处，选择格式并复制! 该密钥用于在解密算法中解密本地存储的凭证文件"
              icon="el-icon-key" cardColor="#4D55CC" style="margin-bottom: 30px;" />

            <!-- 密钥格式选择与复制 -->
            <el-form label-width="100px">
              <el-form-item label="密钥格式">
                <el-select v-model="selectedFormat" placeholder="请选择格式" @change="fetchFormattedKey">
                  <el-option label="C++" value="cpp"></el-option>
                  <el-option label="Java" value="java"></el-option>
                  <el-option label="Python" value="python"></el-option>
                  <el-option label="无格式" value="raw"></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-document-copy" style="margin-left: 10px;"
                  @click="copyKey">复制</el-button>
              </el-form-item>

              <!-- 显示获取到的密钥 -->
              <div>
                <MarkdownWithHighlight :source="formattedKeyMarkdown" />
              </div>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import ColoredCard from '@/components/ColoredCard/index.vue';
import { mapGetters } from 'vuex';
import { changePassword } from '@/api/user'; // 修改密码 API
import { getFormattedKey } from '@/api/keypair'; // 获取格式化密钥 API
import UserCard from './components/UserCard';
import Account from './components/Account';
import MarkdownWithHighlight from '@/components/MarkdownWithHighlight.vue';

export default {
  name: 'Profile',
  components: { UserCard, Account, ColoredCard, MarkdownWithHighlight },
  data() {
    return {
      user: {}, // 用户信息
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      oldPasswordRules: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
      newPasswordRules: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '新密码至少6个字符', trigger: 'blur' }
      ],
      confirmPasswordRules: [
        { required: true, message: '请再输入一遍新密码', trigger: 'blur' },
        { validator: this.validateConfirmPassword, trigger: 'blur' }
      ],
      selectedFormat: '', // 选择的密钥格式
      formattedKey: '', // 远程获取的密钥
      formattedKeyMarkdown: '' // 远程获取的密钥 (MD)
    };
  },
  computed: {
    ...mapGetters(['name', 'avatar', 'roles'])
  },
  created() {
    this.getUser();
  },
  methods: {
    getUser() {
      this.user = {
        name: this.name,
        role: this.roles.join(' | '),
        avatar: this.avatar
      };
    },
    handleSubmit() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          changePassword(
            this.passwordForm.oldPassword,
            this.passwordForm.newPassword,
            this.passwordForm.confirmPassword
          ).then(response => {
            if (response.code === 200) {
              this.$message.success('密码修改成功');
            } else {
              this.$message.error(response.message || '密码修改失败');
            }
          });
        } else {
          this.$message.error('请检查输入的字段');
          return false;
        }
      });
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的新密码不一致'));
      } else {
        callback();
      }
    },
    fetchFormattedKey() {
      if (!this.selectedFormat) {
        this.$message.warning('请选择密钥格式');
        return;
      }
      getFormattedKey(this.selectedFormat)
        .then(response => {
          if (response.code === 200) {
            // 确保换行符正确处理，并格式化为 Markdown 代码块
            this.formattedKey = response.data.key.replace(/\r\n/g, '\n');
            this.formattedKeyMarkdown = '```' + this.selectedFormat + '\n' + this.formattedKey + '\n```';
          } else {
            this.$message.error(response.message || '获取密钥失败');
          }
        })
        .catch(() => {
          this.$message.error('请求密钥时发生错误');
        });
    },
    copyKey() {
      if (!this.formattedKey) {
        this.$message.warning('没有可复制的密钥');
        return;
      }
      navigator.clipboard.writeText(this.formattedKey).then(() => {
        this.$message.success('密钥已复制到剪贴板');
      }).catch(() => {
        this.$message.error('复制失败，请手动复制');
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* Ensuring forms have appropriate spacing */
.password-form {
  max-width: 600px;
  margin: 20px auto;
}

.el-form-item {
  margin-bottom: 20px;
}

/* Responsive card styling */
.responsive-card {
  width: 100%;
  box-sizing: border-box;
}

/* Flex container for card layout (if additional control is needed) */
.card-container {
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

/* Key display styling */
.key-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.key-display .el-button {
  margin-left: 10px;
}
</style>
